package com.example.chat;

import com.example.pojo.Chat;
import com.example.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class UDPClient {
    private static DatagramSocket socket;
    private static InetAddress serverAddress;
    private static int serverPort;                     // 连接服务器UDP端口号
    private static int port;
    private static Socket  socketForServer ;


    @Autowired
    public void setMyProperty(Environment env) {                         //从配置文件中注入静态成员变量

        port = Integer.valueOf(env.getProperty("chat.tcp.port"));
        serverPort = Integer.valueOf(env.getProperty("chat.udp.port"));


        try {
            socket = new DatagramSocket();
            serverAddress = InetAddress.getByName("127.0.0.1");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //客户端向服务端UDP发送消息
    public void sendMessage(Chat chat) {

        try {
            Map<String,String> hashMap = new HashMap<>();
            hashMap.put("jwt",chat.getJwt());
            hashMap.put("message",chat.getMessage());
            byte[] bytes = hashMap.toString().getBytes();
            DatagramPacket packetList = new DatagramPacket(bytes, bytes.length, serverAddress, serverPort);
            socket.send(packetList);

        } catch (IOException e) {
            log.error("发送服务端端口号"+serverPort+"失败！");
        }
    }



    public void ConnectTOServerForTCP(String jwt)  {

        try {
            socketForServer  = new Socket("127.0.0.1", port);
        } catch (IOException e) {
            log.error("登录成功，但是连接失败！");
        }
        Claims claims = JwtUtils.parseJWT(jwt);
        String studentID = (String)claims.get("studentID");
        String name = (String) claims.get("name");

        //创建一个线程用于向服务端连接，循环读取服务端的TCP连接发来的数据
        new Thread(new ClientReceptionForServerRunnable(studentID, name,socketForServer),studentID).start();


    }
}
